package com.abing.permissionsys.controller;

import com.abing.base.BaseResponse;
import com.abing.permissionsys.entity.vo.SysDeptVO;
import com.abing.permissionsys.entity.vo.dept.DeptVO;
import com.abing.permissionsys.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门管理
 *
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2017-09-27 14:40:36
 */

@RestController
@RequestMapping("/dept")
public class DeptController extends BaseController {
	@Autowired
	private DeptService sysDeptService;

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	public BaseResponse save(@RequestBody SysDeptVO sysDept) {
		if (sysDeptService.save(sysDept) > 0) {
			return setResultSuccess();
		}
		return setResultError();
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	public BaseResponse update(@RequestBody SysDeptVO sysDept) {
		if (sysDeptService.update(sysDept) > 0) {
			return setResultSuccess();
		}
		return setResultError();
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove/{id}")
	@ResponseBody
	public BaseResponse remove(@PathVariable Long id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("parentId", id);
		if(sysDeptService.count(map)>0) {
			return setResultError( "包含下级部门,不允许修改");
		}
		if(sysDeptService.checkDeptHasUser(id)) {
			if (sysDeptService.remove(id) > 0) {
				return setResultSuccess();
			}
		}else {
			return setResultError( "部门包含用户,不允许修改");
		}
		return setResultError();
	}

	@PostMapping("/tree")
	@ResponseBody
	public BaseResponse tree(SysDeptVO sysDeptVO) {
		List<DeptVO> deptVO = sysDeptService.getTree(sysDeptVO);
		return setResultSuccess(deptVO);
	}
}
